package com.huluobo.lc.kotlinim1812a.contract.register

import android.util.Log
import cn.bmob.v3.BmobUser
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.SaveListener
import com.huluobo.lc.kotlinim1812a.extenttion.isValidPassword
import com.huluobo.lc.kotlinim1812a.extenttion.isValidUserName
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import org.jetbrains.anko.doAsync

/**
 * @author Lc
 * @description:
 * @date :2021/6/22 10:05
 */
class RegisterPresenter(val view: RegisterContract.View) : RegisterContract.Presenter {
    override fun register(userName: String, password: String, confirmPassword: String) {
        if (userName.isValidUserName()) {
            if (password.isValidPassword()) {
                if (password == confirmPassword) {
                    view.onStartRegister()
                    registerBmob(userName, password)
                } else view.onConfirmPasswordError()
            } else view.onPasswordError()
        } else view.onUserNameError()
    }

    //注册到Bmob相当于向后台发起注册请求 ,由Bmob(后台)发起向环信注册的请求
    private fun registerBmob(userName: String, password: String) {
        val bmobUser = BmobUser()
        bmobUser.username = userName
        bmobUser.setPassword(password)

        bmobUser.signUp(object : SaveListener<BmobUser>() {
            override fun done(bmobUser: BmobUser?, e: BmobException?) {
                if (e == null) {
                    //注册成功
                    Log.i("TagA", "Bmob注册成功")
                    //注册到环信
                    registerEaseMob(userName, password)
                } else {
                    //注册失败
                    if (e.errorCode == 202) {
                        //用户名已存在
                        view.onUserExist()
                    } else {
                        runOnUIThread { view.onRegisterFailed("Bmob注册失败," + e.message) }
                    }

                }
            }
        })
    }

    //模拟公司后台注册流程,正常是不需要我们去环信上注册的
    private fun registerEaseMob(userName: String, password: String) {
        doAsync {
            try {
                //如果不抛出异常,代表注册成功
                EMClient.getInstance().createAccount(userName, password);//同步方法
                runOnUIThread { view.onRegisterSuccess() }
            } catch (e: HyphenateException) {
                //如果捕获异常,代表注册失败
                runOnUIThread { view.onRegisterFailed("环信注册失败," + e.message) }
            }
        }
    }
}